<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>坐席管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in searchParams.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName" v-if="filter.showAble"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare" :disabled="filter.readonly"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" :readonly="filter.readonly" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
        <el-button size="small" type="primary" icon="el-icon-refresh" @click="handleSync()">同步</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border
              element-loading-text="拼命加载中"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column prop="agentnum" label="坐席号码">
      </el-table-column>
      <el-table-column prop="agentname" label="坐席名称">
      </el-table-column>
      <el-table-column prop="state" label="是否占用">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state.value" :disabled="scope.row.state.value == 0" :active-value="1"
                     :inactive-value="0" active-color="#13ce66" @change="changeSeatStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="updateAt" label="更新时间">
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" :disabled="scope.row.state.value == 1"
                     @click="showUserSelector(scope.$index, scope.row)">授权使用
          </el-button>
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteItem(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageParams" @callFather="callFather"/>


    <!-- 新增界面 -->
    <el-dialog :title="editTitle" :visible.sync="editFormVisible" :close-on-click-modal="false" width="30%"
               @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="坐席号码" prop="seatNum">
          <el-input size="small" v-model="editForm.seatNum" placeholder="请输入坐席号码"/>
        </el-form-item>
        <el-form-item label="坐席密码" prop="password">
          <el-input size="small" v-model="editForm.password" auto-complete="off" placeholder="请输入坐席密码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>

    <UserSelector :title="'选择一个用户'" :show-able="selectorParams.showAble"
                  @resultHandler="userSelectorResultHandler" @closeDialog="closeUserSelectorDialog"></UserSelector>

  </div>
</template>

<script>
import {seatAdd, seatDelete, seatEdit, seatList, seatSyncAll} from "../../../api/baseMG";
import Pagination from '../../../components/Pagination'
import UserSelector from "../../../components/UserSelector.vue";

export default {
  data() {
    return {
      selectedItem: {},
      list: [],
      editFormVisible: false,
      editTitle: "",
      loading: false,
      editForm: {},
      rules: {},
      // 分页参数
      pageParams: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      searchParams: {
        orderBy: 'update_at desc',
        page: 1,
        perPage: 10,
        filters: [
          // {
          //   showAble: false,
          //   readonly: true,
          //   placeholder: "默认",
          //   fieldName: "companyId",
          //   compare: "=",
          //   fieldValue: getStore("userInfo").companyId
          // },
          {
            showAble: true,
            readonly: false,
            placeholder: "请输入坐席号码",
            fieldName: "agentnum",
            compare: "like",
            fieldValue: ""
          },
          {
            showAble: false,
            readonly: false,
            fieldName: "queueId",
            compare: "=",
            fieldValue: null
          }
        ],
        isLock: ''
      },
      selectorParams: {
        showAble: false
      }
    }
  },
  created() {
    this.search();
  },
  // 注册组件
  components: {
    UserSelector,
    Pagination
  },
  methods: {
    userSelectorResultHandler(items) {
      let item = items[0];
      this.selectedItem.uid = item.userId;
      this.selectedItem.workNum = item.workNum;
      this.selectedItem.state = 1;
      this.updateItem(this.selectedItem, () => {
        this.selectorParams.showAble = false;
      });
    },
    closeUserSelectorDialog() {
      this.selectorParams.showAble = false;
    },
    showUserSelector(index, row) {
      this.selectedItem = row;
      this.selectorParams.showAble = true;
    },
    changeSeatStatus(row) {
      this.$confirm('确定要释放该坐席吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateItem({id: row.id, state: 0, uid: null});
      }).catch(err => {
        console.error(err);
        this.search(this.formInline);
      })
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog === 'edit') {
        this.editFormVisible = false
      } else if (dialog === 'perm') {
        this.dataAccessshow = false
      } else if (dialog === 'unit') {
        this.unitAccessshow = false
      }
    },
    submitAddForm(params) {
      this.$refs[params].validate(valid => {
          if (valid) {
            if (!this.editForm.id) {
              seatAdd(this.editForm).then(resp => {
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: resp.msg
                  });
                  this.editFormVisible = false;
                  this.search();
                } else {
                  this.$message({
                    type: 'error',
                    message: resp.msg
                  });
                }
              })
            } else {
              this.updateItem(this.editForm);
            }
          }
        }
      );
    },
    handleSync() {
      this.$confirm('同步坐席信息仅新增系统不存在的坐席信息，确定要同步坐席信息吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seatSyncAll().then(resp => {
          if (resp.success) {
            this.$message({
              type: 'success',
              message: resp.msg
            });
          } else {
            this.$message({
              type: 'info',
              message: resp.msg
            })
          }
          this.search();
        })
      });
    },
    handleAdd() {
      this.editTitle = "新增坐席";
      this.editForm = {
        seatNum: '',
        password: ''
      };
      this.editFormVisible = true
    },
    // 分页插件事件
    callFather(param) {
      this.searchParams.page = param.currentPage;
      this.searchParams.perPage = param.pageSize;
      this.getList(this.searchParams);
    },
    handleEdit(index, row) {
      this.editTitle = "修改坐席";
      this.editForm = {
        id: row.id,
        seatNum: row.seatNum,
        password: row.password,
        uid: row.uid,
        workNum: row.workNum
      };
      this.editFormVisible = true
    },
    search() {
      this.initSearchParams();
      this.getList(this.searchParams);
    },
    initSearchParams() {
      console.log(this.$route)
      for (let i = 0; i < this.searchParams.filters.length; i++) {
        let item = this.searchParams.filters[i];
        if(item.fieldName === 'queueId' && this.$route.query.queueId) {
          item.fieldValue = this.$route.query.queueId;
        }
      }
    },
    getList(params) {
      seatList(params).then(resp => {
        if (resp.success) {
          this.list = resp.data.list;
          this.pageParams.currentPage = resp.data.pageNum;
          this.pageParams.pageSize = resp.data.pageSize;
          this.pageParams.total = resp.data.total;
        }
      })
    },
    updateItem(item, c) {
      seatEdit(item).then(res => {
        if (res.success) {
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.search(this.formInline);
          if(c) {
            c();
          }
        } else {
          this.$message({
            type: 'info',
            message: res.msg
          })
        }
      }).catch(err => {
        console.log(err)
        this.loading = false;
        this.$message.error('释放失败，请稍后再试！')
      })
    },
    deleteItem(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seatDelete(row.id).then(res => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: res.msg
            });
            this.search(this.formInline)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        }).catch(err => {
          this.loading = false;
          this.$message.error('删除失败，请稍后再试！')
        })
      }).catch(err => {
        console.error(err);
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}
</style>
